package com.sxt.server.handle;

import com.sxt.server.common.CustomProtocol;
import com.sxt.server.util.NettySession;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HeartBeatSimpleHandle extends ChannelInboundHandlerAdapter {

	private static final ByteBuf HEART_BEAT = Unpooled.unreleasableBuffer(
			Unpooled.copiedBuffer(new CustomProtocol(123456L, "pong").toString(), CharsetUtil.UTF_8));

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		log.info("收到customProtocol={}", msg);
		CustomProtocol customProtocol = (CustomProtocol) msg;
		// 我们调用writeAndFlush（Object）来逐字写入接收到的消息并刷新线路
		// ctx.writeAndFlush(customProtocol);
		// 保存客户端与 Channel 之间的关系
		NettySession.put(customProtocol.getId(), ctx.channel());
	}

	/**
	 * 取消绑定
	 * 
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		NettySession.remove(ctx.channel());
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
			if (idleStateEvent.state() == IdleState.READER_IDLE) {
				log.info("已经50秒没有收到信息！");
				// 向客户端发送消息
				ctx.writeAndFlush(HEART_BEAT).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
			}
		}
		super.userEventTriggered(ctx, evt);
	}
}
